(ns utils.writeDB
	(:import	(java.io FileOutputStream)
				(java.io FileInputStream DataInputStream)
				(java.io RandomAccessFile))
				(:gen-class)
)

(defn pad-string
	"Pads the string to the specified size in bytes (with spaces)."
	[temp-string size]
	(let [string (str temp-string " ") n (- size (.length string))]
		(.substring (apply str string (take n (repeat " "))) 0 size)))

(defn build-db-record
	"Builds a record (string) for the DB with padding."
	[record field-names field-sizes]
	(loop [fn (vec field-names) fs (vec field-sizes) string ""]
		(if (empty? fn)
			string
			(recur (pop fn) (pop fs) (str (pad-string (record (keyword (peek fn))) (peek fs)) string)))))

(defn store-records
	"Stores a new record in the Database file."
	[map filename field-names field-sizes]
	(let [pks (keys map) db (FileOutputStream. filename true)]
		(loop [v1 (vec (reverse pks))]
			(if (empty? v1)
				(.close db)
				(do
					(.write db (. (String. (str (char 0) (char 0) (build-db-record (map (peek v1)) field-names field-sizes))) getBytes))
					(recur (pop v1)))))))

(defn del-record-db
	"Deletes records from the Database file by setting the 'deleted' flag to 0x8000."
	[del-list filename offset field-sizes]
	(let [del-flag 128 file (RandomAccessFile. filename "rw")]
		(loop [lst del-list]
			(if (empty? lst)
				(.close file)
				(let [seek-pos (+ offset (* (dec (peek lst))(apply + 2 field-sizes)))]
					(.seek file (long seek-pos))
					(.write file del-flag)
					(recur (pop lst)))))))

(defn set-record-db
	"Changes fields from the records in the Database file."
	[set-list filename offset field-sizes]
	(let [file (RandomAccessFile. filename "rw")]
		(loop [lst set-list]
			(if (empty? lst)
				(.close file)
				(let [v (peek lst) rec-num (get v 0) f-num (get v 1) string (get v 2)]
					(let [seek-pos (+ offset (* (dec rec-num)(apply + 2 field-sizes)) (apply + 2 (take (dec f-num) field-sizes)))]
						(.seek file (long seek-pos))
						(.writeBytes file (pad-string string (get (vec field-sizes) (dec f-num))))
						(recur (pop lst))))))))